//
//  ZZHomeVC.swift
//  QMXK
//
//  Created by jenkin on 2018/12/3.
//  Copyright © 2018年 jenkin. All rights reserved.
//

import UIKit
import Moya
import HandyJSON
import SnapKit

class ZZHomeVC: ZZBaseVC, UIScrollViewDelegate{
    
    var articleListModel:ZZArticleTypeListModel!
    var topHeadView:UIView!
    var titleScrollView:UIScrollView!
    var mainTextScrollView:UIScrollView!
    var mainScrollViewH:CGFloat!
    var titlebtnArray:Array<UIButton>!
    var textVCArray:Array<ZZHomeTextListVC>!
    var currentVC:ZZHomeTextListVC?
    var ipTextField:UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUI()
        self.loadData()
    }
    
    override func setUI() {
        super.setUI()
        
        let titleY = self.navH
        let titleH = 40 * self.rate
        let topH = titleY + titleH
        self.topHeadView = UIView.init()
        self.view.addSubview(self.topHeadView)
        self.topHeadView.backgroundColor = UIColor.orange
        self.topHeadView.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(0)
            make.height.equalTo(topH)
        }
        
        self.titleScrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: titleY, width: CommenConst.KScreenW, height: titleH))
        self.titleScrollView.showsHorizontalScrollIndicator = false
        self.topHeadView.addSubview(self.titleScrollView)
        
        let mainTextScrollViewH = CommenConst.KScreenH - topH - self.bottomH
        self.mainScrollViewH = mainTextScrollViewH
        self.mainTextScrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: topH, width: CommenConst.KScreenW, height: mainTextScrollViewH))
        self.mainTextScrollView.showsHorizontalScrollIndicator = false
        self.mainTextScrollView.isPagingEnabled = true
        self.mainTextScrollView.delegate = self
        self.view .addSubview(mainTextScrollView)
        
        self.ipTextField = UITextField.init(frame: CGRect.init(x: 20, y: self.navH + 50, width: self.screenW - 40, height: 30))
        self.ipTextField.backgroundColor = UIColor.white
        self.view.addSubview(self.ipTextField)
        self.ipTextField.placeholder = "输入你的IP"
        self.ipTextField.text = ZZBaseUtil.shareUtil.getIpHost()
        
        let ipBtn:UIButton! = UIButton.init(frame: CGRect.init(x: 50, y: self.navH + 100, width: self.screenW - 100, height: 30))
        ipBtn.setTitle("修改IP", for: UIControl.State.normal)
        ipBtn.setTitleColor(UIColor.black, for: UIControl.State.normal)
        self.view.addSubview(ipBtn)
        ipBtn.addTarget(self, action: #selector(ipAction(sender:)), for:  UIControl.Event.touchUpInside)
    }
    
    @objc func ipAction(sender: UIButton){
        
        if (self.ipTextField.text?.count)! > 0{
            ZZBaseUtil.shareUtil.saveIpHost(ipText: self.ipTextField.text!)
            self.view.endEditing(true)
        }
       // if self.ipTextField.text?.count > 0
    }
    
    func loadData(){
        //加载标题
//        weak var weakSelf = self
//        ZZHttpRequest.shareRequest.request(target: MoyaApi.articleType(data: [:]), successBlock: { (data:Dictionary) in
////            weakSelf?.articleListModel = ZZArticleTypeListModel.deserialize(from: data)
////            weakSelf?.refreshTextTitle()
//        },failureBlock:
//        {(data:Dictionary) in
//            print("error")
//        })

//        var data:Dictionary<String, Any> = Dictionary.init();
//        //gid 上海股市以sh开头，深圳股市以sz开头如
//        //type     否     int     0代表上证指数，1代表深证指数
//        data["gid"] = "sh603938"
//        data["key"] = gp_app_key
//        //data["type"] = 0
//        data["page"] = 1
//        //测试加载数据
//        ZZHttpRequest.shareRequest.gpRequest(target: GupiaoAPI.getSHData(data: data), successBlock: { (data:Dictionary) in
//            print(data)
//        },failureBlock:
//            {(data:Dictionary) in
//                print("error")
//        })
    }

    func refreshTextTitle(){
    
        let bW = 60.0 * self.rate
        let bH = 40.0 * self.rate
        let count = self.articleListModel.data.count
        self.titlebtnArray = []
        self.textVCArray = []
        for index in 0..<count{
            let model:ZZArticleTypeModel = self.articleListModel.data[index]
            let button:UIButton = UIButton.init()
            button.tag = index
            self.titlebtnArray.append(button)
            button.setTitle(model.name, for: UIControl.State.normal)
            button.setTitle(model.name, for: UIControl.State.selected)
            button.setTitleColor(ColorConst.shareColorConst.mainTintColor(), for: UIControl.State.selected)
            button.setTitleColor(ColorConst.shareColorConst.titleColor(), for: UIControl.State.normal)
            self.titleScrollView.addSubview(button)
            button.addTarget(self, action:#selector(titleClickAction(button:)), for: UIControl.Event.touchUpInside)
            button.snp.makeConstraints { (make) in
                make.left.equalTo(CGFloat(index) * bW)
                make.top.equalTo(0)
                make.width.equalTo(bW)
                make.height.equalTo(bH)
            }
            
            let textListVC:ZZHomeTextListVC = ZZHomeTextListVC.init(tableStyle:UITableView.Style.plain, tableFrame: CGRect.init(x: CGFloat(index) * self.screenW, y: 0, width: self.screenW, height: self.mainScrollViewH))
            textListVC.artircleModel = self.articleListModel.data[index]
            self.textVCArray.append(textListVC)
            //self.addChild(textListVC)
            //self.mainTextScrollView.addSubview(textListVC.view)
        }
        self.titleScrollView.contentSize = CGSize.init(width: bW * CGFloat(count), height: 0)
        self.mainTextScrollView.contentSize = CGSize.init(width: self.screenW * CGFloat(count), height: 0)
        
        //初始化数据加载
        self.selectBtn(index: 0)
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView == self.mainTextScrollView {
            let index:Int = Int(scrollView.contentOffset.x / CommenConst.KScreenW)
            self.selectBtn(index: index)
        }
    }
    
    @objc func titleClickAction(button: UIButton){
        let index:Int = button.tag
        self.mainTextScrollView.setContentOffset(CGPoint.init(x: CGFloat(index) * CommenConst.KScreenW, y: 0) , animated: false)
        self.selectBtn(index: index)
    }
    
    func selectBtn(index: Int){
        for btn in self.titlebtnArray{
            if btn.tag == index{
                btn.isSelected = true
                continue
            }
            btn.isSelected = false
        }
        
        let newVC:ZZHomeTextListVC = self.textVCArray[index]
        if self.currentVC == nil{
            self.currentVC = newVC
            self.addChild(newVC)
            self.mainTextScrollView.addSubview(newVC.view)
            return
        }
        
        if self.currentVC == newVC{
            return
        }
        
        weak var weakSelf = self
        self.addChild(newVC)
        self.transition(from: self.currentVC!, to: newVC, duration: 0, options: UIView.AnimationOptions.curveEaseIn, animations: nil) { (finish) in
            if finish{
                newVC.removeFromParent()
                newVC.view.removeFromSuperview()
                weakSelf?.addChild(newVC)
                weakSelf?.mainTextScrollView.addSubview(newVC.view)
                weakSelf?.currentVC?.removeFromParent()
                weakSelf?.currentVC?.view.removeFromSuperview()
                weakSelf?.currentVC = newVC
            }else{
                
            }
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
}
